//
//  NativeViewManager.m
//  Unity-iPhone
//
//  Created by Karl on 2017/3/27.
//
//

#import "NativeViewManager.h"
#import "HomePageViewController.h"
#import "ScanViewController.h"
#import "CaptureViewController.h"
#import "InnerWebViewController.h"
#import "InnerWKWebViewController.h"
#import <Social/Social.h>
#import "UIImage+Mix.h"

#define DocPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0]


@implementation NativeViewManager{
    ViewType _currentViewType;
    NSPointerArray *_delegates;
}

+(NativeViewManager *)sharedManager{
    static NativeViewManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NativeViewManager alloc] init];
    });
    return instance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        _showHomePop = YES;
        _delegates = [NSPointerArray weakObjectsPointerArray];
    }
    return self;
}

- (UIWindow *)nativeWindow{
    if (!_nativeWindow) {
        _nativeWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    return _nativeWindow;
}

- (void)view:(ViewType)view show:(BOOL)show{
    
    _currentViewType = view;
    
    switch (view) {
        case ViewTypeHomepage:
            [self homepageShow:show];
            break;
        case ViewTypeScanpage:
            [self scanpageShow:show];
            break;
        case ViewTypeCapturepage:
            [self capturepageShow:show];
            break;
        default:
            break;
    }
}

- (void)targetSceneLoadCompleted:(NSString *)scene{
    NSLog(@"Current Scene is %@",scene);
    
    if ([scene isEqualToString:@"scan"]) {
        
        [HUDManager hide];
        
        switch (_currentViewType) {
            case ViewTypeScanpage:
                NSLog(@"scan scene state SCAN");
//                [self scanpageShow:YES];
                UnitySendMessage("_sceneManager", "LoadScene", "vuforiaAR");
                break;
            case ViewTypeCapturepage:
                NSLog(@"scan scene state CAPTURE");

//                [self capturepageShow:YES];
                UnitySendMessage("_sceneManager", "LoadScene", "liveAR");
                UnitySendMessage("_sceneManager", "LoadLiveARCharacter", "prince");
                break;
            default:
                break;
        }
    }
    
}

- (void)captureCompleted{
    for (id<NativeViewManagerDelegate> delegate in _delegates) {
        if ([delegate respondsToSelector:@selector(captureCompleted)]) {
            [delegate captureCompleted];
        }
    }
}

- (void)showWebWithURL:(NSString *)url inApp:(BOOL)inApp{
    if (inApp) {
        [self showWebWithURL:url];
    }else{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }
}

- (void)showWebWithURL:(NSString *)url{
    
    UIViewController *vc = nil;
    
    if (IOS_VERSION_8_OR_LATER) {
        vc = [[InnerWKWebViewController alloc] initWithUrl:url];

    }else{
        vc = [[InnerWebViewController alloc] initWithUrl:url];

    }
    UINavigationController *nv = [[UINavigationController alloc] initWithRootViewController:vc];
    [[self topViewController] presentViewController:nv animated:YES completion:nil];
}

- (void)shareImage:(UIImage *)image{
    if (![SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
        NSLog(@"不可用");
        return;
    }
    SLComposeViewController *composeVC = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
    [composeVC addImage:image];
    [composeVC setInitialText:@"share test"];
    //    [composeVC addURL:[NSURL URLWithString:@"http://www.baidu.com"]];
    [[self topViewController] presentViewController:composeVC animated:YES completion:nil];
    // 监听用户点击事件
    composeVC.completionHandler = ^(SLComposeViewControllerResult result){
        if (result == SLComposeViewControllerResultDone) {
            NSLog(@"点击了发送");
        }
        else if (result == SLComposeViewControllerResultCancelled)
        {
            NSLog(@"点击了取消");
        }
    };

}
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
    
    
    NSError *error = nil;
    BOOL success = [URL setResourceValue:@(YES)
                                  forKey:NSURLIsExcludedFromBackupKey
                                   error:&error];
    if(!success)
    {
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
    
}
- (UIImage *)captureWithFrame{
    NSString *photoPath = [NSString stringWithFormat:@"%@/CaptureScreen.jpg",DocPath];
    
    [self addSkipBackupAttributeToItemAtURL:[NSURL URLWithString:photoPath]];
    
    UIImage *fImage = [UIImage imageWithContentsOfFile:photoPath];
    
    NSLog(@"capture image size %@",[NSValue valueWithCGSize:fImage.size]);
    
    UIImage *frame =kImgFromFile(@"photo_frame", @"png");
    
    NSLog(@"bg image size %@",[NSValue valueWithCGSize:frame.size]);
    
    UIImage *result = [UIImage mixImageWithFrontImage:fImage andBackImage:frame];
    return result;
}

#pragma mark - Private

- (UIViewController *)topViewController{
    UIViewController *topvc = [UIApplication sharedApplication].keyWindow.rootViewController;
    return topvc;
}
- (void)homepageShow:(BOOL)show{
    if (show) {
        [self.nativeWindow makeKeyAndVisible];
        [self.nativeWindow setRootViewController:[[HomePageViewController alloc] init]];
        return;
    }
    [UnityGetMainWindow() makeKeyAndVisible];
    [_nativeWindow setHidden:YES];
    [_nativeWindow removeFromSuperview];
    _nativeWindow = nil;
//    [UnityGetMainWindow() makeKeyAndVisible];
}
- (void)scanpageShow:(BOOL)show{
    if (show) {
        ScanViewController *vc = [[ScanViewController alloc] init];
        [vc beginAppearanceTransition:YES animated:NO];
        [UnityGetGLViewController() addChildViewController:vc];
        [UnityGetGLViewController().view addSubview:vc.view];
        [vc didMoveToParentViewController:UnityGetGLViewController()];
        [vc endAppearanceTransition];
        
        [self homepageShow:NO];
        
        [HUDManager showInView:nil];
        
        return;
    }
    
    [self homepageShow:YES];
}

- (void)capturepageShow:(BOOL)show{
    if (show) {
        CaptureViewController *vc = [[CaptureViewController alloc] init];
        [vc beginAppearanceTransition:YES animated:NO];
        [UnityGetGLViewController() addChildViewController:vc];
        [UnityGetGLViewController().view addSubview:vc.view];
        [vc didMoveToParentViewController:UnityGetGLViewController()];
        [vc endAppearanceTransition];
        
        [self homepageShow:NO];
        
        [HUDManager showInView:nil];
        
        return;
    }
    
    [self homepageShow:YES];
}

#pragma mark - add/remove delegate
-(void)dealloc {}

-(void)addDelegate:(id<NativeViewManagerDelegate>) delegate
{
    __weak typeof(id<NativeViewManagerDelegate>) weakDelegate = delegate;
    
    [_delegates addPointer:(__bridge void *)(weakDelegate)];
}

-(void)removeDelegate:(id<NativeViewManagerDelegate>) delegate
{
    int rIndex = -1;
    
    for (int index = 0; index < [_delegates count]; index++) {
        
        id<NativeViewManagerDelegate> pDelegate = [_delegates pointerAtIndex:index];
        
        if (pDelegate == nil) {
            
            rIndex = index;
            break;
            
        }
    }
    
    if (rIndex > -1) {
        [_delegates removePointerAtIndex:rIndex];
    }
    
}

@end
